<template>
  <el-dialog
    v-model="visible"
    title="导入"
    width="500"
    destroy-on-close
    append-to-body
  >
    <el-form label-width="80px">
      <el-form-item label="选择文件">
        <XdeFileUploader
          :uploadToFileServer="true"
          :bucket-config="bucketConfig"
          :auto-upload="false"
          @fileList-change="handleFileListChange"
          @upload-complete="handleUploadComplete"
          ref="xdefileuploaderRef"
        />
      </el-form-item>
      <el-form-item label="文件描述">
        <el-input
          v-model="description"
          type="textarea"
          :rows="3"
          placeholder="请输入文件描述（可选）"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click.stop="handleCancel">取消</el-button>
        <el-button type="primary" @click.stop="handleSure">
          确定上传
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
  import { ref, defineExpose, nextTick } from "vue";
  const visible = ref(false);
  const xdefileuploaderRef = ref();
  const emit = defineEmits();

  const bucketConfig = ref([
    {
      bucketName: "sdm",
      objectName: "",
    },
  ]);
  const description = ref("");
  const listFile = ref([]);

  const fileData = ref();

  /**
   * @description 文件上传成功
   *
   */
  const handleUploadComplete = (data: any) => {
    fileData.value = data;
  };

  /**
   * @description 监听文件上传
   */
  const handleFileListChange = async (
    file: any,
    fileList: any,
    callback: any,
  ) => {
    bucketConfig.value = [
      {
        bucketName: "sdm",
        objectName: file?.name ?? "",
      },
    ];
    await nextTick();
    listFile.value = fileList;
    callback({
      bucketName: "sdm",
      objectName: file?.name ?? "",
    });
    await nextTick();
    xdefileuploaderRef?.value?.startUpload?.(file);
  };

  defineExpose({
    visible,
    listFile,
  });
  defineProps([""]);

  /**
   * @description 处理取消
   */
  const handleCancel = () => {
    visible.value = false;
    listFile.value = [];
    xdefileuploaderRef?.value?.clearFileList?.();
    description.value = "";
  };

  /**
   * @description 处理确定
   */
  const handleSure = () => {
    xdefileuploaderRef?.value?.clearFileList?.();
    emit("UploadComplete", {
      ...fileData.value,
      description: description.value,
    });
    description.value = "";
    visible.value = false;
  };
</script>

<style scoped lang="scss">
  @import url("@/components/xde-ui-plus/style.css");
  .footer {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: flex-end;
  }
</style>
